<?php
namespace Todo\Service;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class TokenService extends BaseService
{
    private static $__INSTANCE = null;
    private static $EXPIRED = 1800;

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new TokenService();

        return self::$__INSTANCE;
    }

    
    /**
     * 获取一个空令牌
     * @return string
     */
    public function grantToken($userId, $scope='public'){

        $data = array(
            'code' => $this->generateCode(),
            'user_id' => $userId,
            'scope'   => $scope,
            'add_ip' => get_client_ip(),
            'add_time' => date('Y-m-d H:i:s'),
            'expired_time' => NOW_TIME + self::$EXPIRED
        );
        $model = D('Todo/Sys/Token');
        $data['id'] = $model->add($data);
        if($data['id']) {
            return $data;
        }

        return false;
    }

    /** 更新空令牌的用户信息
     * @param string $token 令牌代码
     * @param int $userId 用户ID
     * @param int $terminalId 终端ID
     * @return bool
     */
    public function updateTokenUser($token, $userId, $terminalId){
        $data = array(
            'user_id' => $userId,
            'terminal_id' => $terminalId,
        );
        return D('Todo/Sys/Token')->where(array('code'=>$token))->save($data) !== false ;
    }

    /** 查询令牌信息
     * @param string $token 令牌代码
     * @return array
     */
    public function getToken($token){
        $key = 'token_code_'.$token;
        $info = S($key);
        if(!$info) $info = D('Todo/Sys/Token')->where(array('code'=>$token))->find(); //缓存中没有，则查询数据库
        if(!$info || $info['expired_time'] <= NOW_TIME) return false;

        S($key, $info); //绑定用户的token进入缓存
        return $info;
    }

    /**
     * 根据令牌，获取当前用户
     * @param String $token 令牌代码
     * @return array
     */
    public function getTokenUser($token){
        $info = $this->getToken($token);
        if(!$info) return null;
        return UserService::getInstance()->cacheFindUser($info['user_id']);
    }

    /**
     * 随机生成代码(md5)
     * @return string
     */
    public function generateCode(){
        return md5(uniqid(). rand(0,100000));
    }

    /**
     * 验证令牌权限
     * @param string $token 令牌代码
     * @param string $scope 权限代码
     * @return bool
     */
    public function checkScope($token, $scope){
        $tokenInfo = $this->getToken($token);
        if(!$tokenInfo || !$tokenInfo['scope'])
        {
            $this->setError('非法令牌或者已经过期');
            return false;
        }

        $scopes = explode(',', $tokenInfo['scope']);
        if(in_array($scope, $scopes)) return true;

        $this->setError('您没有权限');
        return false;
    }

}